package com.qb.hotelTV.Utils;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import java.lang.ref.WeakReference;

/**
 * 安全的Handler类，防止内存泄漏
 * 使用WeakReference持有外部类引用
 */
public class SafeHandler<T> extends Handler {
    
    private WeakReference<T> targetRef;
    private SafeHandlerCallback<T> callback;
    
    public interface SafeHandlerCallback<T> {
        void handleMessage(T target, Message msg);
    }
    
    public SafeHandler(T target, SafeHandlerCallback<T> callback) {
        super(Looper.getMainLooper());
        this.targetRef = new WeakReference<>(target);
        this.callback = callback;
    }
    
    public SafeHandler(T target, Looper looper, SafeHandlerCallback<T> callback) {
        super(looper);
        this.targetRef = new WeakReference<>(target);
        this.callback = callback;
    }
    
    @Override
    public void handleMessage(Message msg) {
        T target = targetRef.get();
        if (target != null && callback != null) {
            callback.handleMessage(target, msg);
        }
    }
    
    /**
     * 清理资源
     */
    public void clear() {
        removeCallbacksAndMessages(null);
        if (targetRef != null) {
            targetRef.clear();
        }
        callback = null;
    }
    
    /**
     * 检查目标是否还存在
     */
    public boolean hasTarget() {
        return targetRef != null && targetRef.get() != null;
    }
    
    /**
     * 安全发送延迟消息
     */
    public boolean sendMessageDelayedSafely(Message msg, long delayMillis) {
        if (hasTarget()) {
            return sendMessageDelayed(msg, delayMillis);
        }
        return false;
    }
    
    /**
     * 安全执行延迟任务
     */
    public boolean postDelayedSafely(Runnable r, long delayMillis) {
        if (hasTarget()) {
            return postDelayed(r, delayMillis);
        }
        return false;
    }
} 